<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\SDK\Iot\V20180120\Models\PubRequest;
use app\admin\model\Cmdlog;
use app\admin\model\Comment;
use app\admin\model\Notice;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdou;
use app\admin\model\Shopks;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptableorder;
use app\admin\model\Shopwifi;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userdoucode;
use app\admin\model\Userkscode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Userweixin;
use app\admin\model\Voice;
use app\api\service\AirService;
use app\api\service\CurlService;
use app\api\service\DouService;
use app\api\service\KsService;
use app\api\service\MeituanService;
use app\api\service\MtService;
use app\api\service\TableService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Shoptable extends Api
{
    protected $noNeedLogin = ['checkAir', 'checkAir2', 'openTableBalanceV3', 'getList', 'sxfOrderCallback', 'chargeNotifySxf', 'checkOrder', 'overOrder', 'checkOrder2', 'overOrderV2'];
    protected $noNeedRight = '*';

    protected $app = null;

    protected $client;

    protected $appKey;
    protected $secret;

    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "awoh1q4tfg29z1yv";
        $this->secret = "b8976219b329b01d543e76a83c923720";
        $config = new \Darabonba\OpenApi\Models\Config([
            // 您的AccessKey ID
            "accessKeyId" => "LTAI5tRwpRY8GgGeFFUDhcpH",
            // 您的AccessKey Secret
            "accessKeySecret" => "JSHHCVXNruyCBlNKk1hPuFimiDAwmR"
        ]);
        // 访问的域名
        $config->endpoint = "iot.cn-shanghai.aliyuncs.com";
        $this->client = new  Iot($config);
    }


    public function getList()
    {

        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $list = $shopTableModel->where('shop_id', $id)->order('id', 'asc')->select();
        $shopOrderModel = new Shoptableorder();
        foreach ($list as $key => $val) {
            $busy = $shopOrderModel->where('table_id', $val['id'])->where('status', 'busy')->find();
            $list[$key]['logo'] = cdnurl($val['logo'], true);
            $list[$key]['rule'] = json_decode($val['rule'], true);
            $list[$key]['status'] = $val['status'];
            if ($busy) {

            } else {
                $list[$key]['min'] = -1;

            }
        }
        $this->success('', $list);
    }


    public function getListV2()
    {

        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $list = $shopTableModel->where('shop_id', $id)->order('weigh', 'asc')->select();
        $shopOrderModel = new Shoptableorder();
        $total = 0;
        foreach ($list as $key => $val) {
            $busy = $shopOrderModel->where('table_id', $val['id'])->where('status', 'doing')->order('book_start', 'desc')->find();
            $list[$key]['logo'] = cdnurl($val['logo'], true);
            $list[$key]['rule'] = json_decode($val['rule'], true);

            $tablePrice = $val['rule'];

            $time1 = $tablePrice['time1'];
            $time2 = $tablePrice['time2'];


            $date = date("Y-m-d");
            $date2 = strtotime("+1 day");
            $time1List = explode("~", $time1);
            if (count($time1List) == 1) {
                $time1List = explode("-", $time1);

            }
            $startTime1 = $date . " " . $time1List[0];
            $endTime1 = $date . " " . $time1List[1];

            if (strtotime($startTime1) > strtotime($endTime1)) {
                $endTime1 = date("Y-m-d", $date2) . " " . $time1List[1];
            }

            $time2List = explode("~", $time2);
            if (count($time2List) == 1) {
                $time2List = explode("-", $time1);

            }
            $startTime2 = $date . " " . $time2List[0];
            $endTime2 = $date . " " . $time2List[1];

            if (strtotime($startTime2) > strtotime($endTime2)) {
                $endTime2 = $date2 . " " . $time2List[1];
            }

            $hourprice = $tablePrice['price2'];
            $currentTime = $time2;
            if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
                $hourprice = $tablePrice['price1'];
                $currentTime = $time1;
            }
            if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
                $hourprice = $tablePrice['price2'];
                $currentTime = $time2;
            }


            $list[$key]['status'] = $val['status'];
            $list[$key]['price'] = $hourprice;
            $list[$key]['time'] = $currentTime;


            //error_log("==busy==".json_encode($busy));

            if ($busy) {
                $one = time();
                $two = strtotime("+" . $busy['min'] . " minute", $busy['book_start']);
                $cle = $two - $one;
                $hours = floor($cle / 3600);
                $minutes = floor(($cle % 3600) / 60);
                $seconds = $cle % 60;
                $list[$key]['status'] = 'busy';

                if ($minutes < 0) {
                    $shopTableModel->where('id', $val['id'])->update(['status' => 'free']);
                    $list[$key]['status'] = 'free';
                }
                $list[$key]['h'] = $hours;
                $list[$key]['m'] = $minutes;
                $list[$key]['s'] = $seconds;

            } else {

                if ($val['status'] == 'busy') {
                    $shopTableModel->where('id', $val['id'])->update(['status' => 'free']);
                    $list[$key]['status'] = 'free';
                }
                $list[$key]['min'] = -1;


            }

            if ($val['status'] == 'free') {
                $total = $total + 1;
            }
        }

        $room_key = "table_count_" . $id;

        $this->longRedis->set($room_key, $total);
        $ret = array();
        $ret['free'] = $total;
        $ret['list'] = $list;

        $this->success('', $ret);
    }

    public function getDetail()
    {

        $userBalanceModel = new Userbalance();

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $detail = $shopTableModel->where('id', $id)->find();
        $shop_id = $detail['shop_id'];
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $detail['tel'] = $shop['tel'];
        $detail['rule'] = json_decode($detail['rule'], true);


        $tablePrice = $detail['rule'];

        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = date("Y-m-d", strtotime("+1 day"));
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = $tablePrice['price2'];
        $currentTime = $time2;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
            $currentTime = $time1;
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price2'];

        }


        $balance = $userBalanceModel->balance($detail['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);

        $detail['balance'] = formatMoney($balance + $allBalance);
        $detail['shop'] = $shop;
        $detail['price'] = $hourprice;


        $this->success('', $detail);
    }


    public function addOrder()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = date("Y-m-d", strtotime("+1 day"));
        $time1List = explode("~", $time1);
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }

        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $orgId = $shop['org_id'];
        $pay_price = $table['ya_amount'];
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $pay_price;
        $db['pay_amount'] = $pay_price;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = time();
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = time();


        $orgModel = new Org();
        $org = $orgModel->where('id', $orgId)->find();

        $shopMnoModel = new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
        $mno = $org['mno'];
        if ($shopMno) {
            if ($shopMno['ratio'] == 100) {
                //走挂靠
                $mno = $shopMno['mno'];
            } else {
                //走分账
                $fusruleId = array();
                $fusruleId['mno'] = $shopMno['mno'];

                $realPay = formatMoney($pay_price - $pay_price * 0.006);
                $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                $fs = array();
                $fs[] = $fusruleId;
                $req['fusruleId'] = $fs;
            }
        }

        $req['mno'] = $mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";


            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];

                $this->success('', $info);
            } else {
                $this->error($bizMsg);
            }

        } else {
            $this->error("订单提交失败");
        }


    }


    public function addOrderV2()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');
        $tuan_id = $this->request->param('tuan_id');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }


        $rule = json_decode($table['rule'], true);

        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $amount = 0;
        $pay_amount = 0;

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        if ($mt_code != "") {

            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    $min = $meituan['hour'] * 60;
                    $amount = $meituan['price'];
                    $pay_amount = 0;

                } else {
                    $this->error("不在时间使用范围内");

                }
            }
        }

        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    $min = $dou['hour'] * 60;
                    $amount = $dou['price'];
                    $pay_amount = 0;
                } else {

                    $this->error("券不在使用时间范围内");
                }
            }

        }


        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $orgId = 27;
        $pay_price = $table['ya_amount'];
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wxcf8801c4f63ea5c5";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            error_log("==sxfPay======" . json_encode($result));
            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];

                $this->success('', $info);
            } else {
                $this->error($bizMsg);
            }

        } else {
            $this->error("订单提交失败");
        }
    }


    public function addOrderHour()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $hour = $this->request->param('hour');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = date("Y-m-d", strtotime("+1 day"));
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];


        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = $tablePrice['price1'];
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price2'];
        }

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($table['shop_id'], $user['id']);


        $book_start = time();
        $min = $hour * 60;
        $amount = formatMoney($hourprice * $hour);
        $pay_amount = formatMoney($hourprice * $hour);
        $endTime = strtotime("+" . $hour . " hour", $book_start);
        $dbBalance = 0;

        if ($balance > 0) {
            if ($balance >= $pay_amount) {
                $dbBalance = $pay_amount;
                $pay_amount = 0;
            }
        }

        if ($amount == 0) $this->error("金额不对无法开台");

        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $orgId = 27;
        $pay_price = $pay_amount;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = 0;
        $db['balance'] = $dbBalance;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = '';
        $db['dou_code'] = '';
        $db['book_end'] = $endTime;
        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wxcf8801c4f63ea5c5";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            if ($pay_amount > 0) {
                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {

                if ($dbBalance == 0) $this->error("开台失败");
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $dbBalance, 'create_time' => time(),
                    'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $dbBalance, 'from' => 'tq']);
                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);

                $tableModel = new \app\admin\model\Shoptable();
                $tableModel->where('id', $table['id'])->update(['status' => 'busy']);
                $order = $tableOrderModel->where('id', $id)->find();
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

                $tableService = new TableService();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);

                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);

                $info['order_no'] = $order_no;
                $info['payInfo'] = "";
                $this->success('', $info);
            }


        } else {
            $this->error("订单提交失败");
        }
    }


    public function sxfOrderCallback()
    {


        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];

        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopTableOrderModel = new Shoptableorder();
            $order = $shopTableOrderModel->where('order_no', $out_trade_no)->find();
            $shopTableOrderModel->where('id', $order['id'])->update(['status' => 'doing']);


            $tableModel = new \app\admin\model\Shoptable();
            $tableModel->where('id', $order['table_id'])->update(['status' => 'busy']);
            //开台

            $deviceModel = new Shopdevice();
            $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

            $order = $shopTableOrderModel->where('order_no', $out_trade_no)->find();
            $tableService = new TableService();
            $tableService->open($order, $device);

            $airService = new AirService();
            $airService->airCheck($order['shop_id']);
            $airService->airCheckV2($order['shop_id'], $order['table_id']);

            if ($order['book_end'] != -1) {

                $shopModel = new \app\admin\model\Shop();
                $shopOrderProfitModel = new Shoporderprofit();
                $shop = $shopModel->where('id', $order['shop_id'])->find();

                $pay_rate = formatMoney($shop['pay_rate'] * $order['pay_amount'] / 100);
                if ($shop['profit_type'] == 1) {
                    $shopProfit = $order['pay_amount'] - $pay_rate;
                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);

                } else {
                    $rate = formatMoney($order['pay_amount'] * $shop['ratio'] / 100);
                    $shopProfit = $order['pay_amount'] - $pay_rate - $rate;
                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                }

                //3. 发分润
//                $pay_rate = formatMoney($shop['pay_rate'] * $order['pay_amount'] / 100);
//                $rate = formatMoney($shop['ratio'] * $order['pay_amount'] / 100);
//                $shopProfit = $order['pay_amount'] - $pay_rate - $rate;
//
//                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
//                    'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
            }
            $this->redis->set($order['shop_id'], time());


        }

    }

    public function getOrderList()
    {

        $user = $this->auth->getUser();
        $page = $this->request->param('page');
        $status = $this->request->param('status');

        $shopModel = new Shop();
        $orderModel = new Shoptableorder();
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['user_id'] = $user['id'];
        if ($status != '') {
            $where['status'] = array('=', $status);
        }

        $list = $orderModel->where($where)->where('status', '<>', 'paying')->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            $order_no = $val['order_no'];
            //查询对应商户手机号
            $shopInfo = $shopModel->where('id', $val['shop_id'])->find();
            if (empty($shopInfo)) {
                $list[$key]['shop_mobile'] = 4008885626;
            } else {
                if (empty($shopInfo['tel'])) {
                    $list[$key]['shop_mobile'] = $shopInfo['mobile'];
                } else {
                    $list[$key]['shop_mobile'] = $shopInfo['tel'];
                }
            }
            $list[$key]['order_no_str'] = substr($order_no, 0, 5) . "*****" . substr($order_no, strlen($order_no) - 4, 4);
            $list[$key]['book_start'] = date("Y-m-d H:i", $val['book_start']);
            if ($val['book_end'] == -1) {
                $list[$key]['book_end'] = "";

            } else {
                $list[$key]['book_end'] = date("Y-m-d H:i", $val['book_end']);

            }
            $list[$key]['create_time_txt'] = date("Y-m-d H:i", $val['create_time']);


            $list[$key]['status_txt'] = $orderModel->formatStatus($val['status']);

        }

        $this->success('', $list);


    }

    public function tableOpenAgain()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }

        if ($order['status'] != "doing") {

            $this->error("此订单无权限打开");
        }

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableService = new TableService();
        $tableService->open($order, $device);

        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);


        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);

        $this->success('成功');
    }


    public function overOrder()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        if ($order['book_end'] == -1) {
            if ($from != 'task') {
                if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {

                    $this->error("", "", "2");
                }
            }
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $rule = json_decode($table['rule'], true);
            $book_end = time();
            $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
            $hour = ceil($minute / 60);
            $start = date("H", $order['book_start']);


            $time1List = explode("~", $rule['time1']);
            if (count($time1List) == 1) {
                $startTime1 = explode("-", $rule['time1'])[0];
                $endTime1 = explode("-", $rule['time1'])[1];
            } else {
                $startTime1 = explode("~", $rule['time1'])[0];
                $endTime1 = explode("~", $rule['time1'])[1];
            }

            $time2List = explode("~", $rule['time2']);
            if (count($time2List) == 1) {
                $startTime2 = explode("-", $rule['time2'])[0];
                $endTime2 = explode("-", $rule['time2'])[1];
            } else {
                $startTime2 = explode("~", $rule['time2'])[0];
                $endTime2 = explode("~", $rule['time2'])[1];
            }


            $startTime1 = intval($startTime1);
            $endTime1 = intval($endTime1);


            $startTime2 = intval($startTime2);
            $endTime2 = intval($endTime2);
            $slots = array();

            if ($endTime1 < $startTime1) {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
            }

            if ($endTime2 < $startTime2) {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
            }

            $hour = floor($minute / 60);

            $orderAmount = $order['pay_amount'];
            $pay_amount = 0;
            if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {

                $orderAmount = 0;
                $amount = $order['amount'];
                $pay_amount = 0;
            } else {
                $amount = get_charge($start, $hour, $slots, $minute);
                if ($amount <= $table['min_amount']) {
                    $amount = $table['min_amount'];
                }
                if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }
            //1.计算费用
            //2.断电
            $mno = $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;


            if ($orderAmount > 0) {

                $userBalanceModel = new Userbalance();

                //如果是余额开台
                if ($order['balance'] > 0 && $order['ya_amount'] == 0) {
                    $pay_amount = 0;
                    $refundAmount = 0;
                    $dbBalance = $amount;
                    $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                    if ($b) {
                        $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                    }
                } else {
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    if ($balance < 0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($balance == 0) {
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;
                        $refundAmount = $order['ya_amount'] - $amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                    } else {

                        if ($amount <= $balance) {
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            error_log("===amount=====" . $amount);
                        } else {
                            $refundAmount = $order['ya_amount'] - ($amount - $balance);
                            $dbBalance = $balance;
                            $dbAmount = $amount - $balance;
                            $pay_amount = $order['ya_amount'] - $refundAmount;

                            $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                            $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                            $shopProfit = $amount - $pay_rate - $rate;

                            if ($shopProfit > 0) {
                                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                    'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                            }

                        }
                        if ($dbBalance > 0) {
                            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                        }
                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                    if ($shopMno && $shopMno['ratio'] == 100) {
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($refundAmount);

                    if ($refundAmount > 0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        $ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            } else {
                //扣余额

                if ($order['dou_code'] != '' || $order['mt_code'] != "") {

                } else {
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                    $db['create_time'] = time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    $userBalanceModel->insert($db);

                }

            }
            $tableOrderModel->where('id', $order['id'])->update(['book_end' => $book_end, 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);

            //关闭
        }
        $tableOrderModel->where('id', $order['id'])->update(['status' => 'done']);
        $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);

        $req = array();

        if ($device['version'] == 1) {
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];


            if ($order['shop_id'] == 107) {

                for ($i = 0; $i < 2; $i++) {
                    sleep(1);
                    $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                }
            } else {
                $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
            }

        } else if ($device['version'] == 2) {
            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        } else if ($device['version'] == 3) {
            $req = array();
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }


        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);

        $this->success('成功');

    }


    public function orderDetail()
    {
        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        //查询对应商户手机号
        $shopModel = new Shop();
        $shopInfo = $shopModel->where('id', $order['shop_id'])->find();
        if (empty($shopInfo)) {
            $order['shop_mobile'] = 4008885626;
        } else {
            if (empty($shopInfo['tel'])) {
                $order['shop_mobile'] = $shopInfo['mobile'];
            } else {
                $order['shop_mobile'] = $shopInfo['tel'];
            }
        }

        $order['order_no_str'] = substr($order_no, 0, 5) . "*****" . substr($order_no, strlen($order_no) - 4, 4);
        $order['book_start'] = date("Y-m-d H:i", $order['book_start']);
        if ($order['book_end'] != -1) {
            $order['book_end'] = date("Y-m-d H:i", $order['book_end']);
        } else {
            $order['book_end'] = "";
        }


        $order['create_time_txt'] = date("Y-m-d H:i", $order['create_time']);

        $order['status_txt'] = $tableOrderModel->formatStatus($order['status']);

        $commentModel = new Comment();
        $comment = $commentModel->where('shop_id', $order['shop_id'])->where('user_id', $order['user_id'])->where('type', 'tq')->where('valid_time', '>', time())->where('status', 'undo')->find();
        $order['is_comment'] = -1;
        if ($comment) {
            if ($order['dou_code'] != "" || $order['mt_code'] != "") {
                $order['is_comment'] = 1;
            }

        }
        $this->success('', $order);
    }

    public function getChargeList()
    {

        $shop_id = $this->request->param('shop_id');
        $shopChargeConfigModel = new Shopchargeconfig();
        $chargeList = $shopChargeConfigModel->where('shop_id', $shop_id)->order('amount', 'asc')->select();
        $this->success('', $chargeList);
    }

    public function doCharge()
    {
        $charge_id = $this->request->param('charge_id');
        $table_id = $this->request->param('table_id');
        $user = $this->auth->getUser();
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $charge['shop_id'])->find();

        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];

        $dbCharge['mark'] = $table_id;
        $dbCharge['pay_rate'] = formatMoney($shop['pay_rate'] * $dbCharge['amount'] / 100);
        $dbCharge['rate'] = formatMoney($shop['ratio'] * $dbCharge['amount'] / 100);

        $pay_price = $charge['amount'];

        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/chargeNotifySxf";

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
            if ($shopMno) {
                $mno = $shopMno['mno'];
            }
            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $orgModel = new Org();
            $org = $orgModel->where('id', $shop['org_id'])->find();
            $mno = $org['mno'];

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
            if ($shopMno) {
                if ($shopMno['ratio'] == 100) {
                    //走挂靠
                    $mno = $shopMno['mno'];
                } else {
                    //走分账
                    $fusruleId = array();
                    $fusruleId['mno'] = $shopMno['mno'];

                    $realPay = formatMoney($pay_price - $pay_price * 0.006);
                    $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                    $fs = array();
                    $fs[] = $fusruleId;
                    $req['fusruleId'] = $fs;
                }
            }

            $req['mno'] = $mno;
            $req['ordNo'] = $order_no;
            $req['amt'] = $charge['amount'];

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];;
            $req['userId'] = $wx['openid'];
            $body = $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = $body;
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            //error_log("=====ret===".json_encode($req));

            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            //error_log("==sxfPay======" . json_encode($result));
            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }

        } else {
            $this->error("充值失败，请联系客服");
        }
    }


    public function chargeNotifySxf()
    {

        $param = file_get_contents("php://input");
        error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {


            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopChargeModel = new Shopcharge();
            $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
            $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
            $userBalanceModel = new Userbalance();
            $shopchargeconfigModel = new Shopchargeconfig();
            $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
                'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $charge['shop_id'])->find();
            $shopOrderProfitModel = new Shoporderprofit();

            if ($shop['profit_type'] == 1) {
                //扣除支付通道费
                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                    'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['amount'] - $order['pay_rate']))]);
            } else {
                //商家分润
                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                    'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['amount'] - $order['rate'] - $order['pay_rate']))]);
                //代理商分润
                if ($shop['agent_ratio'] > 0) {
                    $userOrderProfitModel = new Userorderprofit();
                    $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
                    if ($agentFee > 0) {
                        $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                            'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                    }
                }
            }

//            /**
//             * 商家分润
//             */
//            $shopOrderProfitModel = new Shoporderprofit();
//            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
//                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['amount'] - $order['rate'] - $order['pay_rate']))]);
//
//
//            /**
//             * 代理商分润
//             */
//            if ($shop['agent_ratio'] > 0) {
//
//                $userOrderProfitModel = new Userorderprofit();
//                $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
//                if ($agentFee > 0) {
//                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
//                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
//                }
//
//
//            }

            //

            $shopTableModel = new \app\admin\model\Shoptable();
            $tableOrderModel = new Shoptableorder();

            $table = $shopTableModel->where('id', $order['mark'])->find();

            $balance = $userBalanceModel->balance($table['shop_id'], $order['user_id']);


            $rule = json_decode($table['rule'], true);
            if ($balance > $table['ya_amount']) {
                $book_start = time();
                $tableService = new TableService();
                $min = 0;
                for ($i = 60; $i < 600; $i++) {
                    $book_end = strtotime("+" . $i . " minute", $book_start);
                    $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
                    if ($totalAmount >= $table['ya_amount']) {
                        $min = $i;
                        break;
                    }
                }

                $shop = $shopModel->where('id', $table['shop_id'])->find();

                $pay_price = 0;
                $db = array();
                $db['user_id'] = $order['user_id'];
                $db['table_id'] = $order['mark'];
                $db['shop_id'] = $shop['id'];
                $db['shop_name'] = $shop['name'];
                $db['table_name'] = $table['name'];
                $db['create_time'] = time();
                $db['order_no'] = $order['order_no'];
                $db['amount'] = 0;
                $db['pay_amount'] = 0;
                $db['status'] = 'doing';
                $db['ya_amount'] = 0;
                $db['book_start'] = time();
                $db['balance'] = $table['ya_amount'];
                $db['min'] = $min;

                $id = $tableOrderModel->insertGetId($db);
                $tableModel = new \app\admin\model\Shoptable();
                $tableModel->where('id', $table['id'])->update(['status' => 'busy']);


                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $table['ya_amount'], 'create_time' => time(),
                    'shop_id' => $charge['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $table['ya_amount'], 'from' => 'tq']);


                $order = $tableOrderModel->where('id', $id)->find();
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

                $tableService = new TableService();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);


                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);

            }


        }
    }


    /**
     *  余额开台
     */
    public function openTableBalance()
    {

        $user = $this->auth->getUser();
        $table_id = $this->request->param('table_id');
        $shop_id = $this->request->param('shop_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $table = $shopTableModel->where('id', $table_id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($shop_id, $user['id']);
        if ($table['ya_amount'] > $balance) {
            $this->error("余额不足", "", -2);
        }

        $rule = json_decode($table['rule'], true);
        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $order_no = getOrderSn();
        $shopTableOrderModel = new Shoptableorder();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $table_id;
        $db['shop_id'] = $table['shop_id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = 0;
        $db['pay_amount'] = 0;
        $db['status'] = 'doing';
        $db['ya_amount'] = 0;
        $db['balance'] = $table['ya_amount'];
        $db['book_start'] = time();
        $db['org_id'] = $shop['org_id'];
        $db['min'] = $min;

        $id = $shopTableOrderModel->insertGetId($db);


        $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $table['ya_amount'], 'create_time' => time(),
            'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $table['ya_amount'], 'from' => 'tq']);
        $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);


        $order = $shopTableOrderModel->where('id', $id)->find();
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableService->open($order, $device);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);

        $airService->airCheckV2($order['shop_id'], $order['table_id']);


        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);
        $this->success('', $order_no);

    }

    public function checkOrder()
    {

        //error_log("=======checkOrder========".date("Y-m-d H:i:s"));
        $tableOrderModel = new Shoptableorder();
        $list = $tableOrderModel->where('status', 'doing')->order('create_time', 'asc')->limit(50)->select();
        $cmdModel = new Cmdlog();
        $tableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();

        $voiceModel = new Voice();
        foreach ($list as $key => $val) {

            if ($val['book_end'] == -1) {
                $table = $tableModel->where('id', $val['table_id'])->find();
                $rule = json_decode($table['rule'], true);
                $book_end = time();
                $minute = floor(($book_end - $val['book_start']) % 86400 / 60);
                $start = date("H", $val['book_start']);

                $time1Count = explode("~", $rule['time1']);
                $time2Count = explode("~", $rule['time2']);

                if ($time1Count > 1 && $time2Count > 1) {
                    $startTime1 = explode("~", $rule['time1'])[0];
                    $endTime1 = explode("~", $rule['time1'])[1];

                    $startTime2 = explode("~", $rule['time2'])[0];
                    $endTime2 = explode("~", $rule['time2'])[1];

                    $startTime1 = intval($startTime1);
                    $endTime1 = intval($endTime1);

                    $startTime2 = intval($startTime2);
                    $endTime2 = intval($endTime2);
                    $slots = array();

                    if ($endTime1 < $startTime1) {
                        $obj = array();
                        $obj['begin'] = $startTime1;
                        $obj['end'] = 24;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;
                        $obj = array();
                        $obj['begin'] = 0;
                        $obj['end'] = $endTime1;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;

                    } else {
                        $obj = array();
                        $obj['begin'] = $startTime1;
                        $obj['end'] = $endTime1;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;
                    }

                    if ($endTime2 < $startTime2) {
                        $obj = array();
                        $obj['begin'] = $startTime2;
                        $obj['end'] = 24;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;
                        $obj = array();
                        $obj['begin'] = 0;
                        $obj['end'] = $endTime2;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;

                    } else {
                        $obj = array();
                        $obj['begin'] = $startTime2;
                        $obj['end'] = $endTime2;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;
                    }

                    $currentHour = date("H", time());
                    $currentPrice = 0;
                    foreach ($slots as $slot) {
                        if ($slot["begin"] <= $currentHour && $currentHour < $slot["end"]) {
                            $currentPrice = $slot["charge"];
                        }
                    }
                    $hour = floor($minute / 60);

                    $amount = get_charge($start, $hour, $slots, $minute);
                    $price = $currentPrice * 15 / 60;
                    if ($amount + $price >= $val['ya_amount']) {
                        $msgKey = "table_" . $val['order_no'];
                        $isCount = $this->redis->get($msgKey);
                        if (!$isCount) {
                            $this->redis->set($msgKey, 1, 24 * 60 * 60);
                            $voice = $voiceModel->where('room_id', $val['table_id'])->find();
                            if ($voice) {
                                $cArray = array();
                                $cArray['cmd'] = "voice";
                                $cArray['msg'] = $val['table_name'] . "台只剩下不足15分钟，请尽快续费";
                                $pubRequest = new PubRequest([
                                    "productKey" => "ggy1jAcSplM",
                                    "topicFullName" => "/ggy1jAcSplM/" . "FPD80000101935" . "/user/get",
                                    "messageContent" => base64_encode(json_encode($cArray)),
                                    "iotInstanceId" => "iot-06z00htbh8lvvfe"

                                ]);
                                $resp = $this->client->pub($pubRequest);
                            }
                        }
                    }

                    if ($val['mt_code'] != '' || $val['dou_code'] != '') {
                        if ($val['book_end'] < time()) {
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrderV3";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";

                            Http::post($url, $req);
                        }
                    } else {
                        if ($amount >= $val['ya_amount'] && $val['ya_amount'] != 0) {
                            error_log("===需要续费===" . $val['order_no']);
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrderV3";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";

                            Http::post($url, $req);
                        } else if ($amount >= $val['balance'] && $val['balance'] != 0) {
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrderV3";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";

                            Http::post($url, $req);
                        }
                    }

                }
            } else {
                if ($val['book_end'] < time()) {
                    $url = "https://app.quexiaqp.com/api/app/shoptable/overOrderV3";
                    $req = array();
                    $req['order_no'] = $val['order_no'];
                    $req['from'] = "task";

                    Http::post($url, $req);
                }
            }


        }
        $this->success('成功', $list);
    }


    public function checkOrder2()
    {

        $tableOrderModel = new Shoptableorder();
        $list = $tableOrderModel->where('status', 'doing')->order('create_time', 'asc')->limit(50)->select();
        $cmdModel = new Cmdlog();
        $tableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();

        $voiceModel = new Voice();
        foreach ($list as $key => $val) {


            $table = $tableModel->where('id', $val['table_id'])->find();
            $rule = json_decode($table['rule'], true);
            $book_end = time();
            $minute = floor(($book_end - $val['book_start']) % 86400 / 60);
            $start = date("H", $val['book_start']);


            $time1Count = explode("~", $rule['time1']);
            $time2Count = explode("~", $rule['time2']);

            if ($time1Count > 1 && $time2Count > 1) {
                $startTime1 = explode("~", $rule['time1'])[0];
                $endTime1 = explode("~", $rule['time1'])[1];

                $startTime2 = explode("~", $rule['time2'])[0];
                $endTime2 = explode("~", $rule['time2'])[1];


                $startTime1 = intval($startTime1);
                $endTime1 = intval($endTime1);


                $startTime2 = intval($startTime2);
                $endTime2 = intval($endTime2);
                $slots = array();

                if ($endTime1 < $startTime1) {
                    $obj = array();
                    $obj['begin'] = $startTime1;
                    $obj['end'] = 24;
                    $obj['charge'] = $rule['price1'];
                    $slots[] = $obj;
                    $obj = array();
                    $obj['begin'] = 0;
                    $obj['end'] = $endTime1;
                    $obj['charge'] = $rule['price1'];
                    $slots[] = $obj;

                } else {
                    $obj = array();
                    $obj['begin'] = $startTime1;
                    $obj['end'] = $endTime1;
                    $obj['charge'] = $rule['price1'];
                    $slots[] = $obj;
                }

                if ($endTime2 < $startTime2) {
                    $obj = array();
                    $obj['begin'] = $startTime2;
                    $obj['end'] = 24;
                    $obj['charge'] = $rule['price2'];
                    $slots[] = $obj;
                    $obj = array();
                    $obj['begin'] = 0;
                    $obj['end'] = $endTime2;
                    $obj['charge'] = $rule['price2'];
                    $slots[] = $obj;

                } else {
                    $obj = array();
                    $obj['begin'] = $startTime2;
                    $obj['end'] = $endTime2;
                    $obj['charge'] = $rule['price2'];
                    $slots[] = $obj;
                }

                $currentHour = date("H", time());
                $currentPrice = 0;
                foreach ($slots as $slot) {
                    if ($slot["begin"] <= $currentHour && $currentHour < $slot["end"]) {
                        $currentPrice = $slot["charge"];
                    }
                }
                $hour = floor($minute / 60);

                $amount = get_charge($start, $hour, $slots, $minute);
                $price = $currentPrice * 15 / 60;
                if ($amount + $price >= $val['ya_amount']) {
                    $msgKey = "table_" . $val['order_no'];
                    $isCount = $this->redis->get($msgKey);
                    if (!$isCount) {
                        $this->redis->set($msgKey, 1, 24 * 60 * 60);
                        $voice = $voiceModel->where('room_id', $val['table_id'])->find();
                        if ($voice) {
                            $cArray = array();
                            $cArray['cmd'] = "voice";
                            $cArray['msg'] = $val['table_name'] . "台只剩下不足15分钟，请尽快续费";
                            $pubRequest = new PubRequest([
                                "productKey" => "ggy1jAcSplM",
                                "topicFullName" => "/ggy1jAcSplM/" . "FPD80000101935" . "/user/get",
                                "messageContent" => base64_encode(json_encode($cArray)),
                                "iotInstanceId" => "iot-06z00htbh8lvvfe"

                            ]);
                            $resp = $this->client->pub($pubRequest);
                        }
                    }
                }

                if ($val['mt_code'] != '' || $val['dou_code'] != '') {
                    if ($val['book_end'] < time()) {
                        $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                        $req = array();
                        $req['order_no'] = $val['order_no'];
                        $req['from'] = "task";

                        Http::post($url, $req);
                    }
                } else {
                    if ($amount >= $val['ya_amount'] && $val['ya_amount'] != 0) {
                        error_log("===需要续费===" . $val['order_no']);
                        $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                        $req = array();
                        $req['order_no'] = $val['order_no'];
                        $req['from'] = "task";

                        Http::post($url, $req);
                    } else if ($amount >= $val['balance'] && $val['balance'] != 0) {
                        $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                        $req = array();
                        $req['order_no'] = $val['order_no'];
                        $req['from'] = "task";

                        Http::post($url, $req);
                    }
                }

            }

        }
        $this->success('成功', $list);
    }

    public function addOrder2()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $douCode = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if ($table['status'] == 'busy') $this->error("此台已在使用不可开台");

        $date = date("Y-m-d");
        $startTime = time();

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $hour = -1;
        $mt_dou_price = 0;
        $douVerifyToken = "";
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $table['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                $hour = $dou['hour'];
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();

                $bookEnd = strtotime("+" . $hour . " hour", $bookStart);


                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {

                    error_log($isWeek . "=======douTable==" . $isTime . "====" . $isExist);
                    $mt_dou_price = $dou['price'];
                    $hour = $dou['hour'];
                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($douCode);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }

                } else {
                    $douCode = "";
                }
            }

        }

        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();


        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();

                $bookEnd = strtotime("+" . $hour . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    $mt_dou_price = $meituan['price'];
                    $hour = $meituan['hour'];
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $table['shop_id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不用");
            }
        }


        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }
        $time2List = explode("~", $time2);
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }

        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }

        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $orgId = $shop['org_id'];
        $total_amount = 0;
        if ($douCode != "" || $mt_code != "") {
            $pay_price = 0;
            $ya_price = 0;
            $total_amount = $mt_dou_price;
        } else {
            $pay_price = $table['ya_amount'];
            $ya_price = $table['ya_amount'];
            $total_amount = $table['ya_amount'];
        }
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $total_amount;
        $db['pay_amount'] = $pay_price;
        $db['ya_amount'] = $ya_price;
        $db['book_start'] = time();
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = time();
        $db['dou_code'] = $douCode;
        $db['mt_code'] = $mt_code;
        $db['dou_token'] = $douVerifyToken;

        if ($hour != -1) {
            $db['book_end'] = strtotime("+" . $hour . " hour", time());
        }

        $orgModel = new Org();
        $org = $orgModel->where('id', $orgId)->find();

        $shopMnoModel = new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
        $mno = $org['mno'];
        if ($shopMno) {
            if ($shopMno['ratio'] == 100) {
                //走挂靠
                $mno = $shopMno['mno'];
            } else {
                //走分账
                $fusruleId = array();
                $fusruleId['mno'] = $shopMno['mno'];

                $realPay = formatMoney($pay_price - $pay_price * 0.006);
                $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                $fs = array();
                $fs[] = $fusruleId;
                $req['fusruleId'] = $fs;
            }
        }

        $req['mno'] = $mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";


            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            if ($db['pay_amount'] > 0) {

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                error_log("===res===" . json_encode($res));
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];
                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {
                $info['order_no'] = $order_no;
                $info['payInfo'] = "";
                $shopTableOrderModel = new Shoptableorder();

                $order = $shopTableOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                if ($douCode != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                $order = $shopTableOrderModel->where('order_no', $order_no)->find();
                $shopTableOrderModel->where('id', $order['id'])->update(['status' => 'doing']);

                $tableModel = new \app\admin\model\Shoptable();
                $tableModel->where('id', $order['table_id'])->update(['status' => 'busy']);
                //开台

                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();


//                $req = array();
//                $req['switchOne'] = 1;
//                $req['switchTwo'] = 1;
//                $req['door'] = 1;
//                $req['hello'] = "您好开台成功祝您玩得开心";
//                $req['orderNo'] = $order['order_no'];
//                $req['sn'] = $device['sn'];
//
//                $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
//                $ret = json_decode($ret, true);
//                if ($ret['code'] == 0) {
//                    $msg = "正在打开中";
//                }
                $openTableService = new TableService();
                $openTableService->open($order, $device);

                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

                $this->success('', $info);
            }


        } else {
            $this->error("订单提交失败");
        }


    }


    public function addOrderV3()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');
        $mt_code = trim($mt_code);
        if (!$mt_code) $mt_code = "";
        if (!$dou_code) $dou_code = "";
        $tuan_id = $this->request->param('tuan_id');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }

        $rule = json_decode($table['rule'], true);

        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $amount = 0;
        $pay_amount = 0;

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $pay_price = $table['ya_amount'];
        $douVerifyToken = "";
        $bookEnd = "";
        if ($mt_code != "") {

            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            if (!$mtCode) {
                $req = array();
                $req['code'] = $mt_code;
                $req['shop_id'] = $shop['id'];
                $mtService = new MtService();
                $mtInfo = $mtService->couponInfo($req);

                if ($mtInfo['code'] != 200) {
                    $this->error($mtInfo['msg']);
                }

                $meituanUserCodeModel = new Usermeituancode();

                $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                if ($mtCode['status'] == 'unuse') {
                    $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                }
                $meituanModel = new Shopmeituan();
                $meituan = $meituanModel->where('shop_id', $shop['id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                if (!$mtCode) {
                    $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $mt_code,
                        'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $shop['id']]);
                } else {
                    $mtCode['id'];
                }
                $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    //官方校验美团券
                    $mtReq = array();
                    $mtReq['shop_id'] = $shop['id'];
                    $mtReq['code'] = $mt_code;
                    $mtService = new MtService();
                    $mtInfo = $mtService->couponInfo($mtReq);
                    error_log(json_encode($mtReq) . "===tableOrder===" . json_encode($mtInfo));

                    if ($mtInfo['code'] != 200) {
                        $mt_code = "";
                        $this->error("此券不用");
                    }

                    $min = $meituan['hour'] * 60;
                    $amount = $meituan['price'];
                    $pay_amount = 0;
                    $pay_price = 0;

                } else {
                    $mt_code = "";
                    $this->error("不在时间使用范围内");

                }
            }
        }

        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) {

                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = $this->appKey;
                $tokenReq["client_secret"] = $this->secret;
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                error_log($isWeek . "========" . $isTime . "===exx===" . $isExist);
                if ($isWeek && $isTime && $isExist) {

                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $dou_code = "";
                        $this->error("此券为无效券");
                    }

                    $min = $dou['hour'] * 60;
                    $amount = $dou['price'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {
                    $dou_code = "";
                    $this->error("券不在使用时间范围内");
                }
            }
        }
        $orgId = 27;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;

        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = "wxcf8801c4f63ea5c5";
                $req['userId'] = $wx['openid'];

                $req['subject'] = "台球预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {
                $order = $tableOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $mtService = new MtService();
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);
                $info['order_no'] = $order_no;
                $info['payInfo'] = "";

                $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);
                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);


                $this->success('', $info);


            }


        } else {
            $this->error("订单提交失败");
        }

    }


    public function addOrderV4()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');
        if (!$mt_code) $mt_code = "";
        $tuan_id = $this->request->param('tuan_id');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }


        $rule = json_decode($table['rule'], true);

        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $amount = 0;
        $pay_amount = 0;

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $pay_price = $table['ya_amount'];
        $douVerifyToken = "";
        $bookEnd = "";
        if ($mt_code != "") {

            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) {
                $req = array();
                $req['code'] = $mt_code;
                $req['shop_id'] = $shop['id'];
                $mtService = new MtService();
                $mtInfo = $mtService->couponInfo($req);
                if ($mtInfo['code'] != 200) {
                    $this->error($mtInfo['msg']);
                }

                $meituanUserCodeModel = new Usermeituancode();

                $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                if ($mtCode['status'] == 'unuse') {
                    $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                }
                $meituanModel = new Shopmeituan();
                $meituan = $meituanModel->where('shop_id', $shop['id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                if (!$mtCode) {
                    $id = $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $mt_code,
                        'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);
                } else {
                    $id = $mtCode['id'];
                }
                $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            }
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    //官方校验美团券
                    $mtReq = array();
                    $mtReq['shop_id'] = $shop['id'];
                    $mtReq['code'] = $mt_code;
                    $mtService = new MtService();
                    $mtInfo = $mtService->couponInfo($mtReq);
                    if ($mtInfo['code'] != 200) {
                        $this->error("此券不用");
                    }

                    $min = $meituan['hour'] * 60;
                    $amount = $meituan['price'];
                    $pay_amount = 0;
                    $pay_price = 0;

                } else {
                    $this->error("不在时间使用范围内");

                }
            }
        }

        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }

                    $min = $dou['hour'] * 60;
                    $amount = $dou['price'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {

                    $this->error("券不在使用时间范围内");
                }
            }

        }


        $orgId = 27;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;

        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = "wxcf8801c4f63ea5c5";
                $req['userId'] = $wx['openid'];

                $req['subject'] = "台球预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {
                $order = $tableOrderModel->where('id', $id)->find();
                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);

                if ($mt_code != "") {
                    $mtService = new MtService();
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }

                $info['order_no'] = $order_no;
                $info['payInfo'] = "";

                $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);

                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);
                $this->success('', $info);
            }


        } else {
            $this->error("订单提交失败");
        }

    }


    public function checkTableOrder()
    {
        $user = $this->auth->getUser();
        $tableOrderModel = new Shoptableorder();
        $table = $tableOrderModel->where('status', 'doing')->where('user_id', $user['id'])->find();
        if ($table) {
            if ($table['book_end'] == -1) {
                $this->success('', $table['order_no']);
            } else {
                if ($table['book_end'] != -1 && $table['book_end'] > time()) {
                    $this->success('', $table['order_no']);
                } else {
                    $tableOrderModel->where('id', $table['id'])->update(['status' => 'done']);
                    $this->success("", "");
                }
            }

        } else {
            $this->success("", "");
        }
    }


    public function addOrderV5()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');
        $ks_code = $this->request->param('ks_code');
        if (!$mt_code) $mt_code = "";
        if (!$dou_code) $dou_code = "";
        if (!$ks_code) $ks_code = "";
        $tuan_id = $this->request->param('tuan_id');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }

        $rule = json_decode($table['rule'], true);

        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $amount = 0;
        $pay_amount = 0;

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $pay_price = $table['ya_amount'];
        $douVerifyToken = "";
        $bookEnd = "";
        if ($mt_code != "") {

            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            if (!$mtCode) {
                $req = array();
                $req['code'] = $mt_code;
                $req['shop_id'] = $shop['id'];
                $mtService = new MtService();
                $mtInfo = $mtService->couponInfo($req);

                if ($mtInfo['code'] != 200) {
                    $this->error($mtInfo['msg']);
                }

                $meituanUserCodeModel = new Usermeituancode();

                $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                if ($mtCode['status'] == 'unuse') {
                    $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                }
                $meituanModel = new Shopmeituan();
                $meituan = $meituanModel->where('shop_id', $shop['id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                if (!$mtCode) {
                    $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $mt_code,
                        'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);
                } else {
                    $mtCode['id'];
                }
                $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    //官方校验美团券
                    $mtReq = array();
                    $mtReq['shop_id'] = $shop['id'];
                    $mtReq['code'] = $mt_code;
                    $mtService = new MtService();
                    $mtInfo = $mtService->couponInfo($mtReq);
                    error_log(json_encode($mtReq) . "===tableOrder===" . json_encode($mtInfo));

                    if ($mtInfo['code'] != 200) {
                        $mt_code = "";
                        $this->error("此券不用");
                    }

                    $min = $meituan['hour'] * 60;
                    $amount = $meituan['price'];
                    $pay_amount = 0;
                    $pay_price = 0;

                } else {
                    $mt_code = "";
                    $this->error("不在时间使用范围内");

                }
            }
        }

        $ks_verify_token = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) {

                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = $this->appKey;
                $tokenReq["client_secret"] = $this->secret;
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");
                $shop_id = $shopDou['shop_id'];


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop_id]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop_id]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $dou_code = "";
                        $this->error("此券为无效券");
                    }

                    $min = $dou['hour'] * 60;
                    $amount = $dou['price'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {
                    $dou_code = "";
                    $this->error("券不在使用时间范围内");
                }
            }
        }


        $ks_order_id = "";
        $ks_encrypted_code = "";
        if ($ks_code != "") {
            $userKsCodeModel = new Userkscode();
            $shopKsModel = new Shopks();
            $userKsCode = $userKsCodeModel->where('ks_code', $ks_code)->find();
            $ksReq = array();
            $ksReq['shop_id'] = $table['shop_id'];
            $ksReq['code'] = $ks_code;
            $ksService = new KsService();
            $ksPreResult = $ksService->prepare($this->longRedis, $ksReq);
            $ks_order_id = $ksPreResult['ks_order_id'];
            $ks_encrypted_code = $ksPreResult['encrypted_code'];
            if ($ksPreResult['code'] == 0) $this->error($ksPreResult['msg']);
            if (!$userKsCode) {
                $skuId = $ksPreResult['sku_id'];
                $userKsCodeModel->insert(['user_id' => $user['id'], 'ks_code' => $ks_code, 'create_time' => time(), 'status' => 'unuse', 'sku_id' => $skuId, 'shop_id' => $table['shop_id']]);
                $userKsCode = $userKsCodeModel->where('ks_code', $ks_code)->find();
            } else {
                $userKsCodeModel->where('id', $userKsCode['id'])->update(['user_id' => $user['id'], 'ks_code' => $ks_code, 'create_time' => time(), 'shop_id' => $table['shop_id']]);
            }

            if ($userKsCode['status'] == 'unuse') {
                $ks = $shopKsModel->where('shop_id', $table['shop_id'])->where('sku_id', $userKsCode['sku_id'])->find();
                if (!$ks) $this->error("此券数据不存在");
                $roomIds = json_decode($ks['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $ks['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $ks['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($ks['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    $ks_verify_token = $ksPreResult['verify_token'];
                    $min = $ks['hour'] * 60;
                    $amount = $ks['price'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {
                    $ks_code = "";
                    $ks_verify_token = "";
                    $this->error("券不在使用时间范围内");
                }
            }

        }


        $orgId = 27;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['ks_verify_token'] = $ks_verify_token;
        $db['ks_code'] = $ks_code;

        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = "wxcf8801c4f63ea5c5";
                $req['userId'] = $wx['openid'];

                $req['subject'] = "台球预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {
                $order = $tableOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $mtService = new MtService();
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);
                }

                if ($ks_code != "") {
                    $ksService = new KsService();
                    $ksVerifyReq = array();
                    $ksVerifyReq['verify_token'] = $order['ks_verify_token'];
                    $ksVerifyReq['shop_id'] = $order['shop_id'];
                    $ksVerifyReq['order_no'] = $ks_order_id;
                    $ksVerifyReq['encrypted_code'] = $ks_encrypted_code;
                    $result = $ksService->verify($this->longRedis, $ksVerifyReq);
                    if ($result['code'] == 0) $this->error($result['msg']);
                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd, 'ks_code' => $result['origin_code'], 'amount' => $result['pay_amount']]);
                }
                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);
                $info['order_no'] = $order_no;
                $info['payInfo'] = "";

                $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);
                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);


                $this->success('', $info);


            }


        } else {
            $this->error("订单提交失败");
        }

    }

    public function addOrderHourV2()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $hour = $this->request->param('hour');

        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();

        //跳过时代水岸的小时模式开台
        if ($table['shop_id'] == 107) $this->error('请选择其他模式开台');
        if (!$table) $this->error("桌号不存在");

        //不同用户同时支付，另一个等待30秒
        $key = 'table_qx_' . $id;
        $cache = $this->redis->get($key);
        if ($cache) {
            if ($user['id'] != $cache) {
                $this->error('已经有顾客在支付，请稍后再试');
            }
        } else {
            $this->redis->set($key, $user['id'], 30);
        }

        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tableOrderInfo = $tableOrderModel->where('table_id', $id)->where('status', 'doing')->find();
        if (!empty($tableOrderInfo)) $this->error('台桌正在被使用，无法预定');

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];

        $date = date("Y-m-d");
        $date2 = date("Y-m-d", strtotime("+1 day"));
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];


        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = $tablePrice['price1'];
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price2'];
        }

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($table['shop_id'], $user['id']);
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $balance_type = 0;
        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);


        $book_start = time();
        $min = $hour * 60;
        $amount = formatMoney($hourprice * $hour);
        $pay_amount = formatMoney($hourprice * $hour);
        $endTime = strtotime("+" . $hour . " hour", $book_start);
        $dbBalance = 0;

        if ($balance > 0 || $allBalance > 0) {

            if ($shop['is_join_balance'] == 1) {


                if ($balance >= $pay_amount) {
                    $balance_type = 1;
                    $dbBalance = $pay_amount;
                    $pay_amount = 0;//店铺余额
                } else if ($allBalance >= $pay_amount) {
                    $balance_type = 2;
                    $dbBalance = $pay_amount;
                    $pay_amount = 0;
                } else if ($allBalance + $balance >= $pay_amount) {
                    $balance_type = 3;
                    $dbBalance = $pay_amount;
                    $pay_amount = 0;
                }

            } else {

                if ($balance >= $pay_amount) {
                    $balance_type = 1;
                    $dbBalance = $pay_amount;
                    $pay_amount = 0;
                }


            }
        }

        if ($amount == 0) $this->error("金额不对无法开台");

        $orgId = 27;
        $pay_price = $pay_amount;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = 0;
        $db['balance_type'] = $balance_type;
        $db['balance'] = $dbBalance;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = '';
        $db['dou_code'] = '';
        $db['book_end'] = $endTime;
        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);


        $id = $tableOrderModel->insertGetId($db);
        if ($id) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wxcf8801c4f63ea5c5";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            if ($pay_amount > 0) {
                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    //记录店铺最近下单时间
                    $this->redis->set($shop['id'], time());

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {

                if ($dbBalance == 0) $this->error("开台失败");

                if ($balance_type == 1) {
                    $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $dbBalance, 'create_time' => time(),
                        'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $dbBalance, 'from' => 'tq']);
                } else if ($balance_type == 2) {
                    //扣除平台余额
                    //划拨平台利润给店铺

                    $ratioList = $userAllBalanceModel->cacBalance($user['id'], $dbBalance);
                    $shopProfit = 0;
                    foreach ($ratioList as $key => $val) {
                        $shopProfit += $val['amount'] / $val['ratio'];
                        $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                    }

                    $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                    $shopBalanceProfitModel = new Shopbalanceprofit();
                    $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $id, 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);


                } else if ($balance_type == 3) {

                    $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $balance, 'create_time' => time(),
                        'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $balance, 'from' => 'tq']);

                    $orderAllBalance = $dbBalance - $balance;
                    $ratioList = $userAllBalanceModel->cacBalance($user['id'], $orderAllBalance);
                    $shopProfit = 0;
                    foreach ($ratioList as $key => $val) {
                        $shopProfit += $val['amount'] / $val['ratio'];
                        $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                    }
                    //划拨平台利润给店铺
                    $shopProfit = formatMoney($shopProfit);
                    $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                    $shopBalanceProfitModel = new Shopbalanceprofit();
                    $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $id, 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);


                }

                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);

                $order = $tableOrderModel->where('id', $id)->find();
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();


                $tableModel = new \app\admin\model\Shoptable();
                $tableModel->where('id', $order['table_id'])->update(['status' => 'busy']);

                $tableService = new TableService();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);

                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);

                $info['order_no'] = $order_no;
                $info['payInfo'] = "";

                //记录店铺最近下单时间
                $this->redis->set($order['shop_id'], time());

                $this->success('', $info);
            }


        } else {
            $this->error("订单提交失败");
        }
    }


    public function overOrderV2()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        if ($order['book_end'] == -1) {
            if ($from != 'task') {
                if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {

                    $this->error("", "", "2");
                }
            }
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $rule = json_decode($table['rule'], true);
            $book_end = time();
            $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
            $hour = ceil($minute / 60);
            $start = date("H", $order['book_start']);


            $time1List = explode("~", $rule['time1']);
            if (count($time1List) == 1) {
                $startTime1 = explode("-", $rule['time1'])[0];
                $endTime1 = explode("-", $rule['time1'])[1];
            } else {
                $startTime1 = explode("~", $rule['time1'])[0];
                $endTime1 = explode("~", $rule['time1'])[1];
            }

            $time2List = explode("~", $rule['time2']);
            if (count($time2List) == 1) {
                $startTime2 = explode("-", $rule['time2'])[0];
                $endTime2 = explode("-", $rule['time2'])[1];
            } else {
                $startTime2 = explode("~", $rule['time2'])[0];
                $endTime2 = explode("~", $rule['time2'])[1];
            }


            $startTime1 = intval($startTime1);
            $endTime1 = intval($endTime1);

            $startTime2 = intval($startTime2);
            $endTime2 = intval($endTime2);
            $slots = array();

            if ($endTime1 < $startTime1) {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
            }

            if ($endTime2 < $startTime2) {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
            }

            $hour = floor($minute / 60);

            $orderAmount = $order['pay_amount'];
            $pay_amount = 0;
            if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {

                $orderAmount = 0;
                $amount = $order['amount'];
                $pay_amount = 0;
            } else {
                $amount = get_charge($start, $hour, $slots, $minute);
                if ($amount <= $table['min_amount']) {
                    $amount = $table['min_amount'];
                }
                if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }
            //1.计算费用
            //2.断电
            $mno = $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;

            $userAllBalanceModel = new Userallbalance();
            $userBalanceModel = new Userbalance();
            $shopBalanceProfitModel = new Shopbalanceprofit();

            $is_join_balance = $shop['is_join_balance'];

            if ($orderAmount > 0) {

                //如果是余额开台
                if ($order['balance'] > 0 && $order['ya_amount'] == 0) {

                    if ($order['balance_type'] == 1) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $dbBalance = $amount;
                        $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                        if ($b) {
                            $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                        }
                    } else if ($order['balance_type'] == 2) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $dbBalance = $amount;
                        $ratioList = $userAllBalanceModel->cacBalance($order['id'], $amount);
                        $shopProfit = 0;

                        $userAllBalanceModel->where('order_id', $order['id'])->where('type', 'out')->where('order_type', 'tq')->delete();
                        foreach ($ratioList as $key => $val) {
                            $shopProfit += $val['amount'] / $val['ratio'];
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                        }
                        if ($shopProfit > 0) {
                            $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                            $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                        }

                    } else if ($order['balance_type'] == 3) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                        $dbBalance = 0;
                        if ($b) {
                            $dbBalance = $b['amount'];
                        }

                        $actAmount = $amount - $dbBalance;

                        $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $actAmount);
                        if (count($ratioList) == 0) {

                            error_log("========overOrderV2订单号异常=======" . $order['order_no']);
                        }
                        $shopProfit = 0;

                        $userAllBalanceModel->where('order_id', $order['id'])->where('type', 'out')->where('order_type', 'tq')->delete();
                        foreach ($ratioList as $key => $val) {
                            $shopProfit += $val['amount'] / $val['ratio'];
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                        }
                        if ($shopProfit > 0) {
                            $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                            $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                        }

                        $dbBalance = $amount;

                    }

                } else {
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    $allBalance = $userAllBalanceModel->userBalance($order['user_id']);

                    if ($balance < 0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($balance == 0 && $allBalance == 0) {
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;
                        $refundAmount = $order['ya_amount'] - $amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                    } else {


                        if ($amount <= $balance) {
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            //余额扣款
                            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                        } else if ($amount <= $allBalance && $is_join_balance == 1) {
                            //平台余额扣款
                            $refundAmount = $order['ya_amount'];
                            $pay_amount = 0;
                            $dbBalance = $amount;

                            $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $amount);
                            $shopProfit = 0;
                            foreach ($ratioList as $key => $val) {
                                $shopProfit += $val['amount'] / $val['ratio'];
                                $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                            }
                            if ($shopProfit > 0) {
                                $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                            }


                        } else if ($amount <= ($allBalance + $balance) && $is_join_balance == 1) {
                            //优先店铺余额扣款 再平台余额扣款
                            if ($balance > 0) {
                                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $balance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                            }
                            $dbBalance = $amount;
                            $refundAmount = $order['ya_amount'];
                            $dbAllbalance = $amount - $balance;

                            $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $dbAllbalance);
                            $shopProfit = 0;
                            foreach ($ratioList as $key => $val) {
                                $shopProfit += $val['amount'] / $val['ratio'];
                                $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                            }
                            if ($shopProfit > 0) {
                                $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                            }

                        } else {

                            if ($is_join_balance == 1) {
                                $refundAmount = $order['ya_amount'] - ($amount - $balance - $allBalance);
                                if ($balance > 0) {
                                    $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $balance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                                }
                                $dbBalance = $balance + $allBalance;
                                if ($allBalance > 0) {
                                    $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $allBalance);
                                    $shopProfit = 0;
                                    foreach ($ratioList as $key => $val) {
                                        $shopProfit += $val['amount'] / $val['ratio'];
                                        $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                                    }
                                    if ($shopProfit > 0) {
                                        $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                        $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                                    }
                                }
                                $act = $amount - $balance - $allBalance;
                                $pay_amount = $act;
                                if ($act > 0) {
                                    $pay_rate = formatMoney($shop['pay_rate'] * $act / 100);
                                    $rate = formatMoney($shop['ratio'] * $act / 100);
                                    $shopProfit = $act - $pay_rate - $rate;
                                    if ($shopProfit > 0) {
                                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                                    }
                                }


                            } else {
                                $refundAmount = $order['ya_amount'] - ($amount - $balance);
                                $dbBalance = $balance;
                                $dbAmount = $amount - $balance;
                                $pay_amount = $order['ya_amount'] - $refundAmount;

                                $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                                $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                                $shopProfit = $amount - $pay_rate - $rate;

                                if ($shopProfit > 0) {
                                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                                }
                                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);

                            }


                        }

                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                    if ($shopMno && $shopMno['ratio'] == 100) {
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($refundAmount);

                    if ($refundAmount > 0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        $ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            } else {
                //扣余额

                if ($order['dou_code'] != '' || $order['mt_code'] != "") {

                } else {
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                    $db['create_time'] = time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    $userBalanceModel->insert($db);

                }

            }
            $tableOrderModel->where('id', $order['id'])->update(['book_end' => $book_end, 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);

            //关闭
        }
        $tableOrderModel->where('id', $order['id'])->update(['status' => 'done']);
        $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);

        $req = array();

        if ($device['version'] == 1) {
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            if ($order['shop_id'] == 107) {

                for ($i = 0; $i < 2; $i++) {
                    sleep(1);
                    $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                }
            } else {
                $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
            }

        } else if ($device['version'] == 2) {

            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);

        } else if ($device['version'] == 3) {
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);

        $this->success('成功');
    }

    public function overOrderV3()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        if ($order['book_end'] == -1) {
            if ($from != 'task') {
                if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {

                    $this->error("", "", "2");
                }
            }
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $rule = json_decode($table['rule'], true);
            $tableService = new TableService();
            $order['book_end'] = time();
            $pay_amount = 0;
            if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {
                $orderAmount = 0;
                $amount = $order['amount'];
            } else {
                $amount = $tableService->overCount($order['book_start'], $order['book_end'], $rule);//计算费用
                if ($amount <= $table['min_amount']) {
                    $amount = $table['min_amount'];
                }
                if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }
            //1.计算费用
            //2.断电
            $mno = $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;

            $userAllBalanceModel = new Userallbalance();
            $userBalanceModel = new Userbalance();
            $shopBalanceProfitModel = new Shopbalanceprofit();

            $is_join_balance = $shop['is_join_balance'];

            if ($orderAmount > 0) {
                //如果是余额开台
                if ($order['balance'] > 0 && $order['ya_amount'] == 0) {

                    if ($order['balance_type'] == 1) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $dbBalance = $amount;
                        $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                        if ($b) {
                            $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                        }
                    } else if ($order['balance_type'] == 2) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $dbBalance = $amount;
                        $ratioList = $userAllBalanceModel->cacBalance($order['id'], $amount);
                        $shopProfit = 0;

                        $userAllBalanceModel->where('order_id', $order['id'])->where('type', 'out')->where('order_type', 'tq')->delete();
                        foreach ($ratioList as $key => $val) {
                            $shopProfit += $val['amount'] / $val['ratio'];
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                        }
                        if ($shopProfit > 0) {
                            $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                            $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                        }

                    } else if ($order['balance_type'] == 3) {
                        $pay_amount = 0;
                        $refundAmount = 0;
                        $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                        $dbBalance = 0;
                        if ($b) {
                            $dbBalance = $b['amount'];
                        }

                        $actAmount = $amount - $dbBalance;

                        $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $actAmount);
                        if (count($ratioList) == 0) {

                            error_log("========overOrderV2订单号异常=======" . $order['order_no']);
                        }
                        $shopProfit = 0;

                        $userAllBalanceModel->where('order_id', $order['id'])->where('type', 'out')->where('order_type', 'tq')->delete();
                        foreach ($ratioList as $key => $val) {
                            $shopProfit += $val['amount'] / $val['ratio'];
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                        }
                        if ($shopProfit > 0) {
                            $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                            $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                        }

                        $dbBalance = $amount;

                    }

                } else {
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    $allBalance = $userAllBalanceModel->userBalance($order['user_id']);

                    if ($balance < 0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($balance == 0 && $allBalance == 0) {
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;
                        $refundAmount = $order['ya_amount'] - $amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                    } else {
                        if ($amount <= $balance) {
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            //余额扣款
                            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                        } else if ($amount <= $allBalance && $is_join_balance == 1) {
                            //平台余额扣款
                            $refundAmount = $order['ya_amount'];
                            $pay_amount = 0;
                            $dbBalance = $amount;

                            $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $amount);
                            $shopProfit = 0;
                            foreach ($ratioList as $key => $val) {
                                $shopProfit += $val['amount'] / $val['ratio'];
                                $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                            }
                            if ($shopProfit > 0) {
                                $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                            }


                        } else if ($amount <= ($allBalance + $balance) && $is_join_balance == 1) {
                            //优先店铺余额扣款 再平台余额扣款
                            if ($balance > 0) {
                                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $balance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                            }
                            $dbBalance = $amount;
                            $refundAmount = $order['ya_amount'];
                            $dbAllbalance = $amount - $balance;

                            $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $dbAllbalance);
                            $shopProfit = 0;
                            foreach ($ratioList as $key => $val) {
                                $shopProfit += $val['amount'] / $val['ratio'];
                                $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                            }
                            if ($shopProfit > 0) {
                                $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                            }

                        } else {

                            if ($is_join_balance == 1) {
                                $refundAmount = $order['ya_amount'] - ($amount - $balance - $allBalance);
                                if ($balance > 0) {
                                    $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $balance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                                }
                                $dbBalance = $balance + $allBalance;
                                if ($allBalance > 0) {
                                    $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $allBalance);
                                    $shopProfit = 0;
                                    foreach ($ratioList as $key => $val) {
                                        $shopProfit += $val['amount'] / $val['ratio'];
                                        $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'tq']);
                                    }
                                    if ($shopProfit > 0) {
                                        $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                                        $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                                    }
                                }
                                $act = $amount - $balance - $allBalance;
                                $pay_amount = $act;
                                if ($act > 0) {
                                    $pay_rate = formatMoney($shop['pay_rate'] * $act / 100);
                                    $rate = formatMoney($shop['ratio'] * $act / 100);
                                    $shopProfit = $act - $pay_rate - $rate;
                                    if ($shopProfit > 0) {
                                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                                    }
                                }


                            } else {
                                $refundAmount = $order['ya_amount'] - ($amount - $balance);
                                $dbBalance = $balance;
                                $dbAmount = $amount - $balance;
                                $pay_amount = $order['ya_amount'] - $refundAmount;

                                $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                                $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                                $shopProfit = $amount - $pay_rate - $rate;

                                if ($shopProfit > 0) {
                                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                                }
                                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                            }
                        }

                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                    if ($shopMno && $shopMno['ratio'] == 100) {
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($refundAmount);

                    if ($refundAmount > 0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        $ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            } else {
                //扣余额

                if ($order['dou_code'] != '' || $order['mt_code'] != "") {

                } else {
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                    $db['create_time'] = time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    $userBalanceModel->insert($db);

                }

            }
            $tableOrderModel->where('id', $order['id'])->update(['book_end' => $order['book_end'], 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);

            //关闭
        }
        $tableOrderModel->where('id', $order['id'])->update(['status' => 'done']);
        $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);

        $req = array();

        if ($device['version'] == 1) {
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            if ($order['shop_id'] == 107) {

                for ($i = 0; $i < 2; $i++) {
                    sleep(1);
                    $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                }
            } else {
                $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
            }

        } else if ($device['version'] == 2) {

            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);

        } else if ($device['version'] == 3) {
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);

        $this->success('成功');
    }


    public function openTableBalanceV2()
    {

        $user = $this->auth->getUser();
        $table_id = $this->request->param('table_id');
        $shop_id = $this->request->param('shop_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $table = $shopTableModel->where('id', $table_id)->find();
        if (!$table) $this->error("桌号不存在");
        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($shop_id, $user['id']);
        $balance_type = 0;

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);

        if ($shop['is_join_balance'] == 1) {
            if ($table['ya_amount'] > ($balance + $allBalance)) {
                $this->error("余额不足", "", -2);
            }
        } else {
            if ($table['ya_amount'] > $balance) {
                $this->error("余额不足", "", -2);
            }
        }

        if ($shop['is_join_balance'] == 1) {

            if ($balance >= $table['ya_amount']) {
                $balance_type = 1;
            }
            if ($allBalance >= $table['ya_amount']) {
                $balance_type = 2;
            }
            if ($allBalance + $balance >= $table['ya_amount'] && $balance < $table['ya_amount']) {
                $balance_type = 3;

            }
        } else {
            if ($balance >= $table['ya_amount']) {
                $balance_type = 1;
            }

        }

        $rule = json_decode($table['rule'], true);
        $book_start = time();
        $tableService = new TableService();

        //$min = $tableService->getDuration($book_start, $totalBalance, $rule);

        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $order_no = getOrderSn();
        $shopTableOrderModel = new Shoptableorder();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $table_id;
        $db['shop_id'] = $table['shop_id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = 0;
        $db['balance_type'] = $balance_type;
        $db['pay_amount'] = 0;
        $db['status'] = 'doing';
        $db['ya_amount'] = 0;
        $db['balance'] = $table['ya_amount'];
        $db['book_start'] = time();
        $db['org_id'] = $shop['org_id'];
        $db['min'] = $min;


        $id = $shopTableOrderModel->insertGetId($db);

        if ($balance_type == 1) {
            $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $table['ya_amount'], 'create_time' => time(),
                'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $table['ya_amount'], 'from' => 'tq']);
        } else if ($balance_type == 2) {
            //扣除平台余额
            $allBalance = $userAllBalanceModel->userBalance($user['id']);
            if ($allBalance > 0) {

                $ratioList = $userAllBalanceModel->cacBalance($user['id'], $table['ya_amount']);
                foreach ($ratioList as $key => $val) {
                    $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                }

            }

        } else if ($balance_type == 3) {
            if ($balance > 0) {
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $balance, 'create_time' => time(),
                    'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $balance, 'from' => 'tq']);
            }
            $orderAllBalance = $table['ya_amount'] - $balance;
            if ($allBalance > 0) {
                $shopProfit = 0;
                $ratioList = $userAllBalanceModel->cacBalance($user['id'], $orderAllBalance);
                foreach ($ratioList as $key => $val) {
                    $shopProfit += $val['amount'] / $val['ratio'];

                    $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                }
                if ($shopProfit > 0) {
                    $shopBalanceProfitModel = new Shopbalanceprofit();
                    $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                    $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $id, 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                }
            }

        }

        $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);

        $order = $shopTableOrderModel->where('id', $id)->find();
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableService->open($order, $device);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);

        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);
        $this->success('', $order_no);


    }


    public function checkAir()
    {

        error_log(date("Y-m-d H:i") . "======checkAir========");
        $tableOrderModel = new Shoptableorder();
        $list = $tableOrderModel->where('status', 'done')->where('air_close', 1)->order('create_time', 'desc')->limit(30)->select();

        $airService = new AirService();
        foreach ($list as $key => $val) {
            $airService->airCheckV2($val['shop_id'], $val['table_id']);
        }
        $this->success('成功');
    }

    public function checkAir2()
    {
        $airModel = new \app\admin\model\device\Air();
        $airs = $airModel->where('table_id', '>', 0)
            ->field('device_sn,status,mode,temp,GROUP_CONCAT(DISTINCT table_id SEPARATOR ",") as tableIds')
            ->group('device_sn')
            ->select();

        foreach ($airs as $air) {
            //查询空调伴侣所属台桌
            $tables = explode(',', $air['tableIds']);

            //查询台桌订单
            $shopOrderModel = new Shoptableorder();
            $airServiceModel = new AirService();
            $tableOrders = $shopOrderModel->where('table_id', 'in', $tables)->where('status', 'doing')->select();
            if (empty($tableOrders)) {//关闭对应空调
                if ($air['status'] != -2) {
                    $airServiceModel->operateAir($air, 0);
                    if ($air['status'] == -1) {
                        $airModel->where('device_sn', $air['device_sn'])->update(['status' => -2]);
                    } else {
                        $airModel->where('device_sn', $air['device_sn'])->update(['status' => -1]);
                    }
                }
            } else {//开启空调
                if ($air['status'] != 2) {
                    $airServiceModel->operateAir($air, 1);
                    if ($air['status'] == 1) {
                        $airModel->where('device_sn', $air['device_sn'])->update(['status' => 2]);
                    } else {
                        $airModel->where('device_sn', $air['device_sn'])->update(['status' => 1]);
                    }
                }
            }
        }
        $this->success('执行完成');
    }


    public function openTableBalanceV3()
    {

        $user = $this->auth->getUser();
        $table_id = $this->request->param('table_id');
        $shop_id = $this->request->param('shop_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();

        $table = $shopTableModel->where('id', $table_id)->find();
        if (!$table) $this->error("桌号不存在");

        //不同用户同时支付，另一个等待30秒
        $key = 'table_qx_' . $table_id;
        $cache = $this->redis->get($key);
        if ($cache) {
            if ($user['id'] != $cache) {
                $this->error('已经有顾客在支付，请稍后再试');
            }
        } else {
            $this->redis->set($key, $user['id'], 30);
        }

        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tableOrderModel = new Shoptableorder();
        $tableOrderInfo = $tableOrderModel->where('table_id', $table_id)->where('status', 'doing')->find();
        if (!empty($tableOrderInfo)) $this->error('台桌正在被使用，无法预定');

        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($shop_id, $user['id']);
        $balance_type = 0;

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);

        if ($shop['is_join_balance'] == 1) {

            if ($balance + $allBalance < 10) {
                $this->error("余额不足,最少10元开台", "", -2);
            }
            $totalBalance = $balance + $allBalance;

        } else {
            if ($balance < 10) {
                $this->error("余额不足,最少10元开台", "", -2);
            }
            $totalBalance = $balance;
        }


        if ($shop['is_join_balance'] == 1) {

            if ($balance >= 10) {
                $balance_type = 1;
            }
            if ($allBalance >= 10) {
                $balance_type = 2;
            }
            if ($allBalance + $balance >= 10 && $allBalance > 0) {
                $balance_type = 3;

            }
        } else {
            if ($balance >= 10) {
                $balance_type = 1;
            }

        }

        $rule = json_decode($table['rule'], true);
        $book_start = time();
        $tableService = new TableService();

        $min = $tableService->getDuration($book_start, $totalBalance, $rule);

        //此方法超过1300余额会出错
//        $min = 0;
//        for ($i = 1; $i < 6000; $i++) {
//            $book_end = strtotime("+" . $i . " minute", $book_start);
//            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
//            if ($totalAmount >= $totalBalance) {
//                $min = $i;
//                break;
//            }
//        }

        $order_no = getOrderSn();
        $shopTableOrderModel = new Shoptableorder();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $table_id;
        $db['shop_id'] = $table['shop_id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = 0;
        $db['balance_type'] = $balance_type;
        $db['pay_amount'] = 0;
        $db['status'] = 'doing';
        $db['ya_amount'] = 0;
        $db['balance'] = $totalBalance;
        $db['book_start'] = time();
        $db['org_id'] = $shop['org_id'];
        $db['min'] = $min;
        $id = $shopTableOrderModel->insertGetId($db);

        if ($balance_type == 1) {
            $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $totalBalance, 'create_time' => time(),
                'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $totalBalance, 'from' => 'tq']);
        } else if ($balance_type == 2) {
            //扣除平台余额
            $allBalance = $userAllBalanceModel->userBalance($user['id']);
            if ($allBalance > 0) {

                $ratioList = $userAllBalanceModel->cacBalance($user['id'], $table['ya_amount']);
                foreach ($ratioList as $key => $val) {
                    $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                }

            }

        } else if ($balance_type == 3) {
            if ($balance > 0) {
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out', 'amount' => $balance, 'create_time' => time(),
                    'shop_id' => $table['shop_id'], 'order_id' => $id, "mark" => "台球抵扣押金余额" . $balance, 'from' => 'tq']);
            }
            $orderAllBalance = $table['ya_amount'] - $balance;
            if ($allBalance > 0) {
                $shopProfit = 0;
                $ratioList = $userAllBalanceModel->cacBalance($user['id'], $orderAllBalance);
                foreach ($ratioList as $key => $val) {
                    $shopProfit += $val['amount'] / $val['ratio'];
                    $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $user['id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $id, 'order_type' => 'tq']);
                }
                if ($shopProfit > 0) {
                    $shopBalanceProfitModel = new Shopbalanceprofit();
                    $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                    $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $id, 'create_time' => time(), 'amount' => $shopMoney, 'order_type' => 'tq']);
                }
            }

        }

        $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);

        $order = $shopTableOrderModel->where('id', $id)->find();
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableService->open($order, $device);
        $airService = new AirService();
        $airService->airCheck($order['shop_id']);

        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        //记录店铺最近下单时间
        $this->redis->set($order['shop_id'], time());

        $tableService = new TableService();
        $tableService->updateTableFree($this->longRedis, $order['shop_id']);
        $this->success('', $order_no);


    }


    public function addOrderV6()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');

        $mt_code = str_replace(" ", "", $mt_code);
        $dou_code = str_replace(" ", "", $dou_code);

        if (!$mt_code) $mt_code = "";
        if (!$dou_code) $dou_code = "";
        $tuan_id = $this->request->param('tuan_id');

        //判断美团和抖音券是否同时为空（跳过押金模式）
        if (empty($tuan_id)) {
            if (empty($dou_code) && empty($mt_code)) $this->error('请输入券码');
        }
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $tableOrderModel = new Shoptableorder();

        $table = $shopTableModel->where('id', $id)->find();
        if (!$table) $this->error("桌号不存在");

        //不同用户同时支付，另一个等待30秒
        $key = 'table_qx_' . $id;
        $cache = $this->redis->get($key);
        if ($cache) {
            if ($user['id'] != $cache) {
                $this->error('已经有顾客在支付，请稍后再试');
            }
        } else {
            $this->redis->set($key, $user['id'], 30);
        }

        if ($table['status'] == 'busy') {
            $this->error("此台桌已在使用,无法预定");
        }

        $tableOrderInfo = $tableOrderModel->where('table_id', $id)->where('status', 'doing')->find();
        if (!empty($tableOrderInfo)) $this->error('台桌正在被使用，无法预定');

        $tablePrice = json_decode($table['rule'], true);
        $time1 = $tablePrice['time1'];
        $time2 = $tablePrice['time2'];


        $date = date("Y-m-d");
        $date2 = strtotime("+1 day");
        $time1List = explode("~", $time1);
        if (count($time1List) == 1) {
            $time1List = explode("-", $time1);
        }
        $startTime1 = $date . " " . $time1List[0];
        $endTime1 = $date . " " . $time1List[1];

        if (strtotime($startTime1) > strtotime($endTime1)) {
            $endTime1 = $date2 . " " . $time1List[1];
        }

        $time2List = explode("~", $time2);
        if (count($time2List) == 1) {
            $time2List = explode("-", $time2);
        }
        $startTime2 = $date . " " . $time2List[0];
        $endTime2 = $date . " " . $time2List[1];

        if (strtotime($startTime2) > strtotime($endTime2)) {
            $endTime2 = $date2 . " " . $time2List[1];
        }

        $hourprice = 0;
        if (time() >= strtotime($startTime1) && time() <= strtotime($endTime1)) {
            $hourprice = $tablePrice['price1'];
        }
        if (time() >= strtotime($startTime2) && time() <= strtotime($endTime2)) {
            $hourprice = $tablePrice['price1'];
        }

        $rule = json_decode($table['rule'], true);

        $book_start = time();
        $tableService = new TableService();
        $min = 0;
        for ($i = 60; $i < 600; $i++) {
            $book_end = strtotime("+" . $i . " minute", $book_start);
            $totalAmount = $tableService->cacFee($book_end, $book_start, $rule);
            if ($totalAmount >= $table['ya_amount']) {
                $min = $i;
                break;
            }
        }

        $amount = 0;
        $pay_amount = 0;

        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $meituan_trace_id = "";
        $pay_price = $table['ya_amount'];
        $douVerifyToken = "";
        $bookEnd = "";

        if ($mt_code != "") {

            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            if (!$mtCode) {
                $req = array();
                $req['code'] = $mt_code;
                $req['shop_id'] = $shop['id'];
                $mtService = new MtService();
                if ($shop['mt2_token'] != "") {
                    $meituanService = new MeituanService();
                    $mtInfo = $meituanService->prepare($req);
                    if ($mtInfo['code'] != 200) {
                        $this->error($mtInfo['msg']);
                    }
                    $meituan_trace_id = $mtInfo['traceId'];

                } else {
                    $mtInfo = $mtService->couponInfo($req);
                }
                if ($mtInfo['code'] != 200) {
                    $this->error($mtInfo['msg']);
                }

                $meituanUserCodeModel = new Usermeituancode();

                $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                if ($mtCode['status'] == 'unuse') {
                    $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $mt_code)->find();
                }
                $meituanModel = new Shopmeituan();
                $meituan = $meituanModel->where('shop_id', $shop['id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                if (!$mtCode) {
                    $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $mt_code,
                        'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $shop['id']]);
                } else {
                    $mtCode['id'];
                }
                $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();

            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    //官方校验美团券
                    $mtReq = array();
                    $mtReq['shop_id'] = $shop['id'];
                    $mtReq['code'] = $mt_code;


                    if ($shop['mt2_token'] != "") {
                        $meituanService = new MeituanService();
                        $mtInfo = $meituanService->prepare($mtReq);
                        if ($mtInfo['code'] != 200) {
                            $this->error($mtInfo['msg']);
                        }
                        $meituan_trace_id = $mtInfo['traceId'];
                    } else {
                        $mtService = new MtService();
                        $mtInfo = $mtService->couponInfo($mtReq);
                        if ($mtInfo['code'] != 200) {
                            $mt_code = "";
                            $this->error("此券不用");
                        }
                    }

                    $min = $meituan['hour'] * 60;
                    $amount = $meituan['price'];
                    $pay_amount = 0;
                    $pay_price = 0;

                } else {
                    $mt_code = "";
                    $this->error("不在时间使用范围内");

                }
            }
        }

        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) {

                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = $this->appKey;
                $tokenReq["client_secret"] = $this->secret;
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");

                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                error_log($isWeek . "========" . $isTime . "===exx===" . $isExist);
                if ($isWeek && $isTime && $isExist) {

                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $dou_code = "";
                        $this->error("此券为无效券");
                    }

                    $min = $dou['hour'] * 60;
                    $amount = $dou['price'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {
                    $dou_code = "";
                    $this->error("券不在使用时间范围内");
                }
            }
        }

        $orgId = 27;
        $order_no = getOrderSn();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['table_id'] = $id;
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['table_name'] = $table['name'];
        $db['create_time'] = time();
        $db['order_no'] = $order_no;
        $db['amount'] = $amount;
        $db['pay_amount'] = $pay_amount;
        $db['ya_amount'] = $pay_price;
        $db['book_start'] = $book_start;
        $db['org_id'] = $orgId;
        $db['hour_price'] = $hourprice;
        $db['update_time'] = -1;
        $db['min'] = $min;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;

        $req['mno'] = $this->mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);
        $req['mt_trace_id'] = $meituan_trace_id;

        $id = $tableOrderModel->insertGetId($db);
        if ($id) {
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shoptable/sxfOrderCallback";

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = "wxcf8801c4f63ea5c5";
                $req['userId'] = $wx['openid'];

                $req['subject'] = "台球预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];

                    $this->success('', $info);
                } else {
                    $this->error($bizMsg);
                }
            } else {
                $order = $tableOrderModel->where('id', $id)->find();
                if ($mt_code != "") {
                    $mtService = new MtService();
                    if ($shop['mt2_token'] != "") {
                        $meituanService = new MeituanService();
                        $isChecked = $meituanService->consume($order);
                    } else {
                        $isChecked = $mtService->syncMt($order);

                    }
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                    $userMtCodeModel = new Usermeituancode();
                    $userMtCodeModel->where('mt_code', $order['mt_code'])->update(['status' => 'used']);

                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                    //添加抖音券表的订单ID
                    $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);

                    $tableOrderModel->where('id', $id)->update(['status' => 'doing', 'book_end' => $bookEnd]);

                }
                $tableOrderModel->where('id', $id)->update(['status' => 'doing']);
                $info['order_no'] = $order_no;
                $info['payInfo'] = "";

                $shopTableModel->where('id', $table['id'])->update(['status' => 'busy']);
                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
                $tableService->open($order, $device);

                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);
                $tableService = new TableService();
                $tableService->updateTableFree($this->longRedis, $order['shop_id']);

                //记录店铺最近下单时间
                $this->redis->set($order['shop_id'], time());

                $this->success('', $info);


            }


        } else {
            $this->error("订单提交失败");
        }

    }


}
